package edu.gatech.coc.sirana.parser;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

import net.util.Debug;

/**
 * 
 * @author Paul
 *
 */
public class ClientLogParser {
	private ArrayList<OneWebPageInteractionLogParser> allWebPageLogItems;
	
	public ClientLogParser(String clientLogFile) throws IOException{
		this.allWebPageLogItems	= new ArrayList<OneWebPageInteractionLogParser>();
		this.doParse(clientLogFile);
	}
	
	public ArrayList<ClientLogItem> parseLogItems(){
		ArrayList<ClientLogItem> interactions = new ArrayList<ClientLogItem>();
		
		
		for (OneWebPageInteractionLogParser owp : this.allWebPageLogItems){
			ArrayList<ClientLogItem> itemsInOnePage = owp.getInteractions();
			
			for (int i=0; i<itemsInOnePage.size(); i++){
				ClientLogItem c = itemsInOnePage.get(i);
				
				if (c.isLeaveEvent()){
//					interactions.add(c);
				}else if (c.isTextarea() && interactions.size() > 0 && interactions.get(interactions.size()-1).isTextarea()){
					//don't add
				}else{
//					Debug.println("Event: " + c.getEvent());
					interactions.add(c);
				}
			}
		}
		
		Collections.sort(interactions);
		
		for (int i=0; i<interactions.size(); i++){
			interactions.get(i).setId(i+1);
		}
		
		
		return interactions;
	}
	
	
	
	private void doParse(String srcFile) throws IOException{
		FileReader fileReader = new FileReader(srcFile);
		BufferedReader bufferReader = new BufferedReader( fileReader );	
		
		OneWebPageInteractionLogParser opilp;
		ArrayList<String> onePageContentStrings = new ArrayList<String>();
		while (true){
			String oneLine = bufferReader.readLine();
		
//			Debug.println("--parse line:\n\t" + oneLine);
			if (oneLine != null) {			
				if (oneLine.trim().length() != 0){
					onePageContentStrings.add( oneLine );
//					Debug.println( oneLine );
				}
				else{
					opilp	= new OneWebPageInteractionLogParser(onePageContentStrings);
					this.allWebPageLogItems.add(opilp);	
					
					onePageContentStrings = new ArrayList<String>();
				}	
			}else{ 
				if (onePageContentStrings.size() == 0) break;
				
				opilp	= new OneWebPageInteractionLogParser(onePageContentStrings);	
				
				this.allWebPageLogItems.add(opilp);				
				onePageContentStrings = null;
				
				break;
			}
		}	
		
	}
	
	public String toString(){
		StringBuffer sb	= new StringBuffer();
		for (OneWebPageInteractionLogParser opilp: this.allWebPageLogItems){
			sb.append(opilp.toString());
		}
	
		return sb.toString();
	}
}
